package first.endtoend

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64
import first.endtoend.messages.MessageCode
import org.springframework.dao.DataIntegrityViolationException

class RationCardController
{

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    Agent agentInstance

    def scaffold = true

    def index()
    {
        redirect(action: "list", params: params)
    }

    def list(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        [rationCardInstanceList: RationCard.list(params), rationCardInstanceTotal: RationCard.count()]
    }

    def create(Long id)
    {
        try
        {
            def family = Family.get(id)
            if (!family) throw new Exception("Not found")
            def rationCardInstance = family.rationCard ? family.rationCard : new RationCard(params)
            rationCardInstance.tag = !rationCardInstance.tag ? new Tag() : rationCardInstance.tag
            rationCardInstance.tag.type = 'BENEFICIARY'
            rationCardInstance.family = family
            [rationCardInstance: rationCardInstance]


        }
        catch (NumberFormatException e)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'family.label', default: 'Family'), params['family.id']])
            redirect(action: "list")
        }
        catch (Exception e)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'family.label', default: 'Family'), params['family.id']])
            redirect(action: "list")
        }

    }

    def save()
    {

        EncryptDecrypt encryptDecrypt = new EncryptDecrypt()



        params.validity = Date.parse('yyyy/mm/dd', params.validity)
        def rationCardInstance = new RationCard(params)
        println "PARAMS RATION CARD" + params.type + " " + params.tagId
        def tag = new Tag(type: params.type, tagId: params.tagId)
        println tag
        byte[] encryptedTagId = Base64.decode(tag.tagId)
        println "ENCRYPTED = " + encryptedTagId.toString()
        // String decryptedTagId=encryptDecrypt.decrypt(encryptedTagId)
        // tag.tagId=decryptedTagId
        tag.save()
        rationCardInstance.tag = tag
        Family familyInstance = rationCardInstance.family
        FairPricesShop fpsInstance

        if (tag)
        {
            if (tag.save(flush: true))
            {
                rationCardInstance.tag = tag
                if (!rationCardInstance.save(flush: true))
                {
                    flash.message = message(code: 'default.invalid.creditCard.message')
                    render(view: "create", model: [rationCardInstance: rationCardInstance])
                    return
                }
                rationCardInstance.family.rationCard = rationCardInstance
                rationCardInstance.family.save(flush: true)
                if (familyInstance)
                {
                    fpsInstance = familyInstance.fps
                } else
                {
                }
                if (fpsInstance)
                {
                    agentInstance = Agent.findByFps(fpsInstance)

                }

                Notification notificationInstance
                if (agentInstance && familyInstance.rationCard != null)
                {
                    notificationInstance = new Notification(agent: agentInstance, idModel: familyInstance.id, code: MessageCode.FAMILY_UPDATE.value(), modelName: Family.getSimpleName(), description: message(code: 'rationCard.add.message' + familyInstance.familyName, default: "There is a new RationCard for Family")).save()
                } else
                {

                }
                flash.message = message(code: 'default.created.message', args: [message(code: 'rationCard.label', default: 'RationCard'), rationCardInstance.id])
                redirect(action: "show", controller: "family", params: [id: params['family.id'] as Long, idRationCard: rationCardInstance.id as Long])
                return
            } else
            {
                flash.message = "Unable to save Tag" << tag?.errors?.each { it }
                render(view: "create", model: [rationCardInstance: rationCardInstance])
                return
            }
        }
        flash.message = "Tag not exist"
        render(view: "create", model: [rationCardInstance: rationCardInstance])
    }

    def show(Long id)
    {
        def rationCardInstance = RationCard.get(id)
        if (!rationCardInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'rationCard.label', default: 'RationCard'), id])
            redirect(action: "list")
            return
        }

        [rationCardInstance: rationCardInstance]
    }

    def edit(Long id)
    {
        println(params)
        def rationCardInstance = RationCard.get(id)
        if (!rationCardInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'rationCard.label', default: 'RationCard'), id])
            redirect(action: "list")
            return
        }

        [rationCardInstance: rationCardInstance, tagInstance: rationCardInstance?.tag]
    }

    def update(Long id, Long version)
    {
        def rationCardInstance = RationCard.get(id)
        Family familyInstance = rationCardInstance.family
        FairPricesShop fpsInstance

        if (!rationCardInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'rationCard.label', default: 'RationCard'), id])
            redirect(action: "list")
            return
        }

        if (version != null)
        {
            if (rationCardInstance.version > version)
            {
                rationCardInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                        [message(code: 'rationCard.label', default: 'RationCard')] as Object[],
                        "Another user has updated this RationCard while you were editing")
                render(view: "edit", model: [rationCardInstance: rationCardInstance])
                return
            }
        }

        rationCardInstance.properties = params

        if (!rationCardInstance.save(flush: true))
        {
            render(view: "edit", model: [rationCardInstance: rationCardInstance])
            return
        }

        if (familyInstance)
        {
            fpsInstance = familyInstance.fps
        } else
        {
        }
        if (fpsInstance)
        {
            agentInstance = Agent.findByFps(fpsInstance)

        }

        Notification notificationInstance
        if (agentInstance && familyInstance.rationCard != null)
        {
            notificationInstance = new Notification(agent: agentInstance, idModel: familyInstance.id, code: MessageCode.FAMILY_UPDATE.value(), modelName: Family.getSimpleName(), description: message(code: 'rationCard.update.message' + familyInstance.familyName, default: "There is an update of RationCard for Family")).save()
        } else
        {

        }
        flash.message = message(code: 'default.updated.message', args: [message(code: 'rationCard.label', default: 'RationCard'), rationCardInstance.id])
        redirect(action: "show", id: rationCardInstance.id)
    }

    def delete(Long id)
    {
        def rationCardInstance = RationCard.get(id)
        Family familyInstance = rationCardInstance.family
        FairPricesShop fpsInstance

        if (!rationCardInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'rationCard.label', default: 'RationCard'), id])
            redirect(action: "list")
            return
        }

        try
        {
            rationCardInstance.delete(flush: true)
            if (familyInstance)
            {
                fpsInstance = familyInstance.fps
            } else
            {
            }
            if (fpsInstance)
            {
                agentInstance = Agent.findByFps(fpsInstance)

            }

            Notification notificationInstance
            if (agentInstance && familyInstance.rationCard != null)
            {
                notificationInstance = new Notification(agent: agentInstance, idModel: familyInstance.id, code: MessageCode.FAMILY_UPDATE.value(), modelName: Family.getSimpleName(), description: message(code: 'rationCard.delete.message' + familyInstance.familyName, default: "There is a delete of RationCard for Family")).save()
            } else
            {

            }
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'rationCard.label', default: 'RationCard'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e)
        {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'rationCard.label', default: 'RationCard'), id])
            redirect(action: "show", id: id)
        }
    }

}
